/**
 * Created by mayousheng on 2016/11/21.
 *
 *
 * 每个页面api.js请求唯一调用函数
 * 统一规划管理
 */

import fetch from 'isomorphic-fetch';
import _ from '../util/index';

export default (url = '/', methodType = 'GET', params = {}) => {
    var adminId = window.cloudshop_adminId;
    var jwtToken = window.cloudshop_jwtToken;
    let options = {
        headers: {
            'Content-Type': 'application/json',
            "x-client-type": 'a',
            "x-href": window.location.href,
            "x-uid": adminId.substring(1),
            'adminId': adminId,
            'Authorization': jwtToken
        },
        mode:"cors",
        method: methodType
    };

    if (methodType.toLocaleUpperCase() === 'GET' && params) {
        /**
         * fetch 不支持get的时候附带参数
         * 需要这里手动追加在url里,作为 query params
         */
        if (!_.isEmptyObject(params)) {
            let aParams = [];
            Object.keys(params).forEach((key) => {
                if (params.hasOwnProperty(key)) {
                    aParams.push(`${key}=${params[key]}`);
                }
            })
            let mark = '?';
            if (url.indexOf('?') !== -1) {
                mark = "&";
            }

            url += mark + aParams.join("&");
        }
    } else {
        options.body = JSON.stringify(params);
    }

    url = $CONST_HOST.v_cloudshop_api.concat(url);
    return fetch(url, options).then(data => {
        return data.json();
    }).then(json => {
        if (json.ok == false || (json.status && json.status !== 200 && json.error)) {
            return Promise.reject(json);
        }
        return json.data;
    }).catch(error => {
        if(error.code == 'C-4030008' || error.code == 'C-40300082') {
            error.message = '用户已删除或已被锁定'
        }
        return Promise.reject(error)
    });
}
